package com.example.wemedia.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.common.util.R;
import com.example.common.util.ResultCodeRecord;
import com.example.model.wemedia.dto.LoginDto;
import com.example.model.wemedia.pojo.User;
import com.example.utils.common.JwtUtil;
import com.example.wemedia.mapper.UserMapper;
import com.example.wemedia.service.UserService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.HashMap;
import java.util.Map;

@Service
public class UserServiceImpl extends ServiceImpl< UserMapper, User > implements UserService {
    @Override
    public Map<String, Object> login(LoginDto dto) {
        //1.检查参数
        if(StringUtils.isBlank(dto.getUserName()) || StringUtils.isBlank(dto.getPassword())){
            R.error(ResultCodeRecord.PARAM_INVALID,"用户名或密码为空");
        }

        //2.查询用户
        User user = getOne(Wrappers.< User >lambdaQuery().eq(User::getUserName, dto.getUserName()));
        if(user == null){
            R.error(ResultCodeRecord.DATA_NOT_EXIST);
        }

        //3.比对密码
        String salt = null;
        if (user != null) {
            salt = user.getUserSalt();
        }
        String pswd = dto.getPassword();
        pswd = DigestUtils.md5DigestAsHex((pswd + salt).getBytes());
        Map<String,Object> map  = new HashMap<>();
        if (user != null && pswd.equals(user.getPassword())) {
            //4.返回数据  jwt
            user.setUserSalt(null);
            user.setPassword(null);
            map.put("user", user);
            map.put("token", JwtUtil.getToken(user.getUserId().longValue()));
            return map;
        }
        return map;
    }
}